<template>
  <div class="recoder-wrap">
    <!-- 实时音频录制 -->
    <audio class="record-audio" controls v-if="mp3Blob" v-bind="$attrs">
      <source :src="audioUrl" type="audio/mp3" />
    </audio>
    <el-button type="primary" size="mini" @click="start" v-if="!recording && !mp3Blob"
      >开始录制</el-button
    >
    <el-button type="danger" size="mini" @click="stop" v-if="recording">完成录制</el-button>
    <span class="left-gap record-time" v-if="recording">{{ recordTime }}</span>
    <div class="left-gap-wrap" v-if="mp3Blob">
      <el-button @click="reset" size="mini" v-if="mp3Blob">重置</el-button>
      <el-button class="left-gap" size="mini"  type="primary" @click="upload"
        >上传</el-button
      >
      <el-progress
        class="record-progress"
        v-if="showProgress"
        :text-inside="true"
        :stroke-width="16"
        :percentage="progressValue"
        v-bind="$attrs"
      ></el-progress>
    </div>
    <!-- <div class="recorder-log">{{recordLog}}</div> -->
  </div>
</template>

<script>
import MP3Recorder from "@/js/recordmp3";
export default {
  data() {
    return {
      //上传文件的进度显示与基本信息
      progressValue: 0,
      showProgress: false,
      // 录音实例
      recorder: null,
      // 是否正在录音中
      recording: false,
      // 录音文件blob & 是否生成音频文件
      mp3Blob: null,
      // 音频url
      audioUrl: "",
      // 录音时长
      recordTime: "00:00:00",
      // 录音时长计时器
      timer: null,
    };
  },
  methods: {
    initRecord() {
      this.recorder = new MP3Recorder({
        debug: true,
        funOk: () => {
          this.recordLog = "初始化成功";
          this.recorder?.start?.();
          this.recording = true;
          this.recordLog = "录音开始...";
          this.timeCount();
        },
        funCancel: (msg) => {
          this.recordLog = msg;
          this.recorder = null;
          this.$message.error(`开启录音失败：${msg}`);
        },
      });
    },
    // 开始录制
    start() {
      this.initRecord();
    },
    // 停止录制
    stop() {
      // 停止录制
      this.recorder?.stop?.();
      this.timer && clearInterval(this.timer);
      this.recording = false;
      this.recordLog = "录音结束，MP3导出中...";
      this.recorder?.getMp3Blob?.((blob) => {
        this.recordLog = "MP3导出成功";
        this.mp3Blob = blob;

        //获取文件的播放路径
        let url = null;
        if (window.createObjectURL != undefined) {
          url = window.createObjectURL(this.mp3Blob);
        } else if (window.URL != undefined) {
          url = window.URL.createObjectURL(this.mp3Blob);
        } else if (window.webkitURL != undefined) {
          url = window.webkitURL.createObjectURL(this.mp3Blob);
        }

        this.audioUrl = url;
      });
    },
    // 重置
    reset() {
      this.mp3Blob = null;
      this.audioUrl = "";
      this.showProgress = false;
      this.progressValue = 0;
      this.$emit("reset");
    },
    // 上传
    // async upload() {
    upload() {
      const formData = new FormData();
      const fileName = encodeURIComponent("audio_recording.mp3");
      const file = new File([this.mp3Blob], fileName, {
        type: this.mp3Blob.type,
      });

      if (!file) {
        this.$message.error("请先录制有效的音频文件");
        return;
      }

      if (file.fileSize > 1024 * 20) {
        this.$message.error("音频文件大小不能大于20M");
        return;
      }

      // 选择文件后，开始上传
      this.showProgress = true;
      formData.append("myFiles", file);
      formData.append("file", file);
      formData.append("fileType", 0);
      formData.append("title", fileName);

      // const res = await Api.uploadFile({
      //   data: formData,
      //   loading: false,
      //   timeout: 1000000,
      //   onUploadProgress: (progressEvent) => {
      //     this.progressValue =
      //       ((progressEvent.loaded / progressEvent.total) * 100) | 0;
      //   },
      // });

      // if (+res.code === 200) {
      //   if (!res.data || !res.data.detailInfoModel) {
      //     this.$message.error("数据读取异常");
      //     return;
      //   }
      //   const data = res?.data || {};
      //   // 传出上传的文件数据
      //   this.$emit("upload", { data, fileName });
      // } else {
      //   this.$message.error(res.message || res.msg || "上传失败");
      // }
    },
    timeCount() {
      // 录音计时
      let tempTime = 0;
      let second = 0;
      let minute = 0;
      let hour = 0;
      this.timer = setInterval(() => {
        tempTime += 1;
        second = Math.floor(tempTime % 60); // 转秒
        minute = Math.floor(tempTime / 60) % 60; // 转分钟
        hour = Math.floor(tempTime / 60 / 60) % 24; // 转小时

        // 格式化
        second = (second > 9 ? second : "0" + second) + "";
        minute = (minute > 9 ? minute : "0" + minute) + "";
        hour = (hour > 9 ? hour : "0" + hour) + "";

        this.recordTime = hour + ":" + minute + ":" + second;
      }, 1000);
    },
  },
  beforeDestroy() {
    this.timer && clearInterval(this.timer);
    this.recorder?.stop?.();
  },
};
</script>

<style lang="less" scoped>
@deep: ~">>>";
.recoder-wrap {
  width: 100%;
  margin-bottom: 15px;
  font-size: 14px;
  .record-audio {
    height: 34px;
    width: 380px;
    vertical-align: middle;
    margin-right: 15px;
  }
  .record-time {
    color: #fc5a5a;
  }
  .left-gap {
    margin-left: 15px;
  }
  .left-gap-wrap {
    margin-top: 15px;
  }
  .record-progress {
    width: 248px;
    display: inline-block;
    margin-left: 15px;
  }
  .btn-action {
    padding-left: 15px;
  }
}
</style>

